package com.cmc6.websocket.config;

import cn.hutool.core.thread.ThreadUtil;
import com.cmc6.common.constant.BaseConstant;
import com.cmc6.common.properties.Cmc6AdminProperties;
import com.cmc6.websocket.service.SocketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class WebSocketApplicationRunnerConfig implements ApplicationRunner {

    public static Integer WEBSOCKET_PORT; // websocket 端口号
    public static String socketSufKey; // ip:port
    public static String socketKey; // PRE_REDIS_SOCKET_REG + ip:port + :

    @Resource
    SocketService socketService;
    @Resource
    Cmc6AdminProperties cmc6AdminProperties;

    @Value("${server.port:8080}")
    private void setPort(Integer value) {
        WebSocketApplicationRunnerConfig.WEBSOCKET_PORT = value + 1; // 加个 1表示socket的ip地址
        WebSocketApplicationRunnerConfig.socketSufKey =
            cmc6AdminProperties.getSocketAddress() + ":" + WebSocketApplicationRunnerConfig.WEBSOCKET_PORT; // ip:port
        WebSocketApplicationRunnerConfig.socketKey =
            BaseConstant.PRE_REDIS_SOCKET_REG + WebSocketApplicationRunnerConfig.socketSufKey
                + ":"; // PRE_REDIS_SOCKET_REG + ip:port + :
    }

    @Override
    public void run(ApplicationArguments args) {
        ThreadUtil.execute(() -> {
            socketService.offlineAllForCurr(); // 全部离线
            new NettyServer().start(); // 启动 netty服务，备注：这里会阻塞线程
        });

        log.info("netty-websocket 启动完成：" + socketSufKey);
    }
}
